//var ajax_url = 'http://app.taocitong.top/Api';
var ajax_url = 'http://test.taocitong.top/Api'; //测试服

var wx_url = 'http://app.taocitong.top';
//var wx_url = 'http://test.taocitong.top';//测试服

/*
 *常用函数
 */


function time(){
    var timestamp3 = Date.parse(new Date());
    return timestamp3/1000;
}


function imgload() {
    $("img.lazy").lazyload({
        effect: "fadeIn",
        threshold: 0
    });
    $('.lazy').removeClass('lazy');
}


function get_pic(type,callback,quality,target){
    if (!quality) {
        quality = 95;
    }
    if (!target) {
        target = 1024
    }
    api.getPicture({
        sourceType: type,
        mediaValue: 'pic',
        destinationType: 'url',
        allowEdit: false,
        quality: quality ,
        targetWidth: target,
        targetHeight: target,
        saveToPhotoAlbum: false
    }, function (ret, err) {
        if (ret) {
            if (ret.data == "") {
                return;
            }else{
                callback(ret.data);
            }
        } else {
            console.log(JSON.stringify(err));
        }
    });
}



function notification (content, params) {
    api.notification({
        notify: {
            title: '淘瓷通',
            content: content,
            extra: params,
            updateCurrent: false
        }
    }, function (ret, err) {

        //alert(JSON.stringify(ret));
    });
    speechRecognizer = api.require('speechRecognizer');
    speechRecognizer.read({
        readStr: content,
        speed: 50,
        volume: 100,
        voice: 'xiaoyan',
        rate: 16000,
        audioPath: 'fs://speechRecogniser/read.mp3'
    }, function (ret, err) {
        //alert(JSON.stringify(ret));
        if (ret.status) {
            ret.speakProgress
        } else {
            api.alert({msg: err.msg});
        }
    });
}

function al (res) {
    api.alert({
        title: '数据展示',
        msg: JSON.stringify(res),
    });
}

function play_music (url,id) {
    if (url.substring(0, 4) == "http") {
        api.download({
            url: url
        }, function (ret, err) {
            if (ret.state == 1) {
                cl("下载完成");
                api.startPlay({
                    path: ret.savePath
                }, function (ret, err) {
                    if (ret) {
                        cl("播放完成");
                        $('#hsb'+id).attr('src', '../img/shengbo.png');
                    } else {
                        cl(err);
                    }
                });
            } else {
                cl(err);
            }
        });
    } else {
        api.startPlay({
            path: url
        }, function (ret, err) {
            if (ret) {
                cl("播放完成");
            } else {
                cl(err);
            }
        });
    }
}

function play_video (url) {
    var videoPlayer = api.require('videoPlayer');
    videoPlayer.play({
        texts: {
            head: {
                title: '视频播放'
            }
        },
        path: url,
        autorotation: true,
        autoPlay: true
    });
}

function setFresh () {
    api.setRefreshHeaderInfo({
        visible: true,
        loadingImg: 'widget://img/fresh.png',
        bgColor: '#FFF',
        textColor: '#000',
        showTime: false,
        textDown:'',
        textUp:"松开刷新",
        textLoading:"加载中",
        showTime:false
    }, function (ret, err) {
        fresh();
    });
}

function auto_login (callback) {
    console.log("执行自动登录");
    api.ajax({
        url: ajax_url + "/login",
        method: 'post',
        data: {
            values: {
                "username": localStorage.username,
                "password": localStorage.password
            }
        }
    }, function (ret, err) {
        if (ret) {
            cl(ret);
            if (ret.isSuccess == 1) {
                localStorage.token = ret.data.token;
                localStorage.loginName = ret.data.user.loginName;
                localStorage.headIco = ret.data.user.headIco;
                if (callback) {
                    setTimeout(function () {
                        callback();
                    }, 300)
                }
            } else {
                api.hideProgress();
                api.refreshHeaderLoadDone();
                toast(ret.res);
            }
        } else {
            api.hideProgress();
            api.refreshHeaderLoadDone();
            toast(JSON.stringify(err.msg));
        }
    });
}

function ajax_file (url, params, files, callback) {
    api.showProgress({
        style: 'default',
        animationType: 'fade',
        title: '请稍后',
        text: '数据加载中...',
        modal: true
    });

    api.ajax({
        url: ajax_url + url,
        method: 'post',
        data: {
            values: params,
            files: files
        }
    }, function (res, err) {
        cl(err);
        console.log('访问接口：'+url);
        console.log('发送参数：'+JSON.stringify(files));
        console.log('返回结果：'+JSON.stringify(res));
        api.hideProgress();
        api.refreshHeaderLoadDone();
        if (callback) {
            callback(res);
        }
    });
}



function ajax (url, params, callback) {
    
    params.time = Date.now();
    if (localStorage.user_id && localStorage.user_id != "") {
        params.user_id = localStorage.user_id;
        params.city_id = localStorage.city_id;
        params.sub_id = localStorage.sub_id;
        params.user_type = localStorage.user_type;
    }
    api.showProgress({
        style: 'default',
        animationType: 'fade',
        title: '请稍后',
        text: '数据加载中...',
        modal: true
    });
    console.log('访问接口：'+ajax_url + url);
    console.log('发送参数：'+JSON.stringify(params));
    api.ajax({
        url: ajax_url + url,
        method: 'post',
        headers: {
            Authorization: localStorage.token
        },
        data: {
            values: params
        }
    }, function (res, err) {
        api.hideProgress();
        api.refreshHeaderLoadDone();
        if (res) {
            //console.log('返回结果：'+JSON.stringify(res));
            if (res.isSuccess == 0) {
                toast(res.msg);
            }else if (res.isSuccess == 1) {
                api.hideProgress();
                api.refreshHeaderLoadDone();
                //console.log('返回成功，进行回调');
                if (callback) {
                    callback(res);
                    $('#wangluo').hide();
                }
            }
        } else {
            //alert(JSON.stringify(err.msg)); //网络状态码
            $('#wangluo').show();
            $('#wangluo').html('网络连接失败,请检查您的网络!');

        }
    });
}

function lookpic (list, index) {
    api.openWin({
        name: 'lookpic',
        url: 'widget://html/look_pic_win.html',
        pageParam: {
            list:list,
            index:index
        }
    });
}


function openWeb (url) {
    var browser = api.require('webBrowser');
    browser.open({
        url: url + '?id=' + localStorage.user_id,
        titleBar:{
            bg:'#e51c23',
            textColor:'#FFFFFF'
        }
    });
}


function autoCopyText(content){
    var clipBoard = api.require('clipBoard');
    clipBoard.set({
        value: content
    }, function(ret, err) {
        if (ret.status) {
            toast('已复制到剪切板')
        } else {
            toast('复制失败');
        }
    });
}

function getCopyText(){
    var clipBoard = api.require('clipBoard');
    clipBoard.get(function(ret, err) {
        if (ret) {
            return ret.value;
        } else {
            alert(JSON.stringify(err));
        }
    });
}

function openWin (name, title, bounces, params) {
    if (!params) {
        params = {};
    }
    api.openWin({
        name: name,
        url: 'widget://html/window.html',
        allowEdit:true,
        pageParam: {
            name: name,
            title: title,
            bounces: bounces,
            params: params
        }
    });
}

function openFram(url,title,params){
    if (!params) {
        params = {};
    }
    api.openFrame({
        name: url,
        url: 'widget://html/'+url+'.html',
        rect: {
            x: 0,
            y: 0,
            w: 'auto',
            h: 'auto'
        },
        pageParam: {
            name: 'test'
        }
    });
}


function back () {
    api.closeWin();
}

function toast (content) {
    api.toast({
        msg: content,
        duration: 2000,
        location: 'bottom'
    });
}


function setValue(obj) {
    if (obj.value == 100) {
        obj.value = 0;
    }
    setTimeout(function() {
        arcProgress.setValue({
            id: obj.id,
            value: ++obj.value
        });
        setValue(obj)
    }, 100);
}

var UIActionProgress;

function upload_img(path,callback){
    console.log(path);
    UIActionProgress = api.require('UIActionProgress');
    UIActionProgress.open({
        maskBg: 'rgba(0,0,0,0.5)',
        styles: {
            h: 108,
            bg: '#fff',
            title: {
                size: 13,
                color: '#000',
                marginT: 10
            },
            msg: {
                size: 12,
                color: '#000',
                marginT: 5
            },
            lable: {
                size: 12,
                color: '#696969',
                marginB: 5
            },
            progressBar: {
                size: 2,
                normal: '#000',
                active: '#4876FF',
                marginB: 35,
                margin: 5
            }
        },
        data: {
            title: '正在上传',
            msg: '请稍后',
            value: 0
        }
    },function(ret){
        //api.alert({msg:JSON.stringify(ret)});
    });

    var aliyunOSS = api.require('aliyunOSS');
    aliyunOSS.initOSSClient({
        endpoint : 'http://oss.taocitong.top',
        accessKeyId : 'LTAInof5hCrxcKCP',
        accessKeySecret:"NfBKRKCQkI7EBUq2wlTd22kT2jU0Mz",
    },function(ret,err){
      if(ret){
            var name =  new Date().getTime()+''+Math.ceil(Math.random()*100000)+".jpg";
            aliyunOSS.upload({
                file : path,
                bucketName : "taocitong",
                objectKey :name,
                uploadType :1,
            }, function(ret, err) {
                cl(ret);
                if (ret.progress) {

                    UIActionProgress.setData({
                        data: {
                            title: '正在上传',
                            msg: '请稍后',
                            value: ret.progress
                        }
                    });
                }
                if(ret.oper){
                    UIActionProgress.close();
                    console.log('http://oss.taocitong.top/'+name);
                    callback('http://oss.taocitong.top/'+name);
                }
            });
        }
    });
}

var videoCompression;
function upload_video(path,thumbnail,callback){
    UIActionProgress = api.require('UIActionProgress');
    videoCompression = api.require('videoCompression')
    
    UIActionProgress.open({
        maskBg: 'rgba(0,0,0,0.5)',
        styles: {
            h: 108,
            bg: '#fff',
            title: {
                size: 13,
                color: '#000',
                marginT: 10
            },
            msg: {
                size: 12,
                color: '#000',
                marginT: 5
            },
            lable: {
                size: 12,
                color: '#696969',
                marginB: 5
            },
            progressBar: {
                size: 2,
                normal: '#000',
                active: '#4876FF',
                marginB: 35,
                margin: 5
            }
        },
        data: {
            title: '正在压缩',
            msg: '请稍后',
            value: 0
        }
    },function(ret){
        //api.alert({msg:JSON.stringify(ret)});
    });
    if(api.systemType == 'ios'){
        var quality='high';
    }else{
        var quality='medium';
    }
    videoCompression.compression({
        path: path,
        quality: quality
    }, function(ret) {
        if(ret.eventType == 'completed'){
            cl(path);
            var path = ret.path
            var aliyunOSS = api.require('aliyunOSS');
            aliyunOSS.initOSSClient({
                endpoint : 'http://oss.taocitong.top',
                accessKeyId : 'LTAInof5hCrxcKCP',
                accessKeySecret:"NfBKRKCQkI7EBUq2wlTd22kT2jU0Mz",
            },function(ret,err){
              if(ret){
                    var name =  new Date().getTime()+''+Math.ceil(Math.random()*100000)+".mp4";
                    aliyunOSS.upload({
                        file : path,
                        bucketName : "taocitong",
                        objectKey :name,
                        uploadType :1,
                    }, function(ret, err) {
                        cl(ret);
                        if (ret.progress) {
                            UIActionProgress.setData({
                                data: {
                                    title: '正在上传',
                                    msg: '请稍后',
                                    value: ret.progress
                                }
                            });
                        }
                        if(ret.oper){
                            var thum =new Date().getTime()+''+Math.ceil(Math.random()*100000)+".jpg";
                            aliyunOSS.upload({
                                file : thumbnail,
                                bucketName : "taocitong",
                                objectKey :thum,
                                uploadType :1,
                            }, function(ret, err) {
                                cl(ret);
                                if (ret.progress) {
                                    UIActionProgress.setData({
                                        data: {
                                            title: '正在上传',
                                            msg: '请稍后',
                                            value: ret.progress
                                        }
                                    });
                                }
                                if(ret.oper){
                                    UIActionProgress.close();
                                    console.log('http://oss.taocitong.top/'+name);
                                    callback('http://oss.taocitong.top/'+name,'http://oss.taocitong.top/'+thum);
                                }
                            });
                            // console.log('http://oss.taocitong.top/'+name);
                            // callback('http://oss.taocitong.top/'+name);
                        }
                    });
                }
            });
    
            
        }else if(ret.eventType == 'exporting'){
            cl(ret);
            UIActionProgress.setData({
                data: {
                    title: '正在压缩等待上传',
                    msg: '请稍后',
                    value: ret.progress
                }
            });
            
        } else {
            api.alert({msg:JSON.stringify(ret)});
        }
    });  
}

function upload_img_watermark(path,callback){  //添加水印
    console.log(path);
    UIActionProgress = api.require('UIActionProgress');
    UIActionProgress.open({
        maskBg: 'rgba(0,0,0,0.5)',
        styles: {
            h: 108,
            bg: '#fff',
            title: {
                size: 13,
                color: '#000',
                marginT: 10
            },
            msg: {
                size: 12,
                color: '#000',
                marginT: 5
            },
            lable: {
                size: 12,
                color: '#696969',
                marginB: 5
            },
            progressBar: {
                size: 2,
                normal: '#000',
                active: '#4876FF',
                marginB: 35,
                margin: 5
            }
        },
        data: {
            title: '正在上传',
            msg: '请稍后',
            value: 0
        }
    },function(ret){
        //api.alert({msg:JSON.stringify(ret)});
    });
  
    var aliyunOSS = api.require('aliyunOSS');
    aliyunOSS.initOSSClient({
        endpoint : 'http://oss.taocitong.top',
        accessKeyId : 'LTAInof5hCrxcKCP',
        accessKeySecret:"NfBKRKCQkI7EBUq2wlTd22kT2jU0Mz",
    },function(ret,err){
      if(ret){
          var json={
                "oldimgurl":path,
                "newimgurl":path,
               "newimgwidth":"800",
                "fontnum":"2",
                "font0x":"100",
                "font0y":"100",
                "font0words":"仅用于淘瓷通APP审核专用",
                "font0size":"40",
                "font0color":"#000000",
                "font0style":"宋体",
                "font1x":"150",
                "font1y":"500",
                "font1words":"仅用于淘瓷通APP审核专用",
                "font1size":"40",
                "font1color":"#000000",
                "font1style":"隶书",
                "imgnum":"2"
              
            };
          var mobilePrint=api.require('mobilePrint');
             mobilePrint.imgPrint(json,function(res) {

                var name =  new Date().getTime()+''+Math.ceil(Math.random()*100000)+".jpg";
                aliyunOSS.upload({
                    file : res.imgurl,
                    bucketName : "taocitong",
                    objectKey :name,
                    uploadType :1,
                }, function(ret, err) {
                    cl(ret);
                    if (ret.progress) {
                        UIActionProgress.setData({
                            data: {
                                title: '正在上传',
                                msg: '请稍后',
                                value: ret.progress
                            }
                        });
                    }
                    if(ret.oper){
                        UIActionProgress.close();
                        console.log('http://oss.taocitong.top/'+name);
                        callback('http://oss.taocitong.top/'+name);
                        
                    }
                });
             console.log(JSON.stringify(res));
            });
        }
    });
}


function many_image_oss(path,callback){
    console.log(path);
    var aliyunOSS = api.require('aliyunOSS');
    aliyunOSS.initOSSClient({
        endpoint : 'http://oss.taocitong.top',
        accessKeyId : 'LTAInof5hCrxcKCP',
        accessKeySecret:"NfBKRKCQkI7EBUq2wlTd22kT2jU0Mz",
    },function(ret,err){
      if(ret){
            var name =  new Date().getTime()+''+Math.ceil(Math.random()*100000)+".jpg";
            aliyunOSS.upload({
                file : path,
                bucketName : "taocitong",
                objectKey :name,
                uploadType :1,
            }, function(ret, err) {
                cl(ret);
                if (ret.progress) {
                }
                if(ret.oper){
                    console.log('http://oss.taocitong.top/'+name);
                    callback('http://oss.taocitong.top/'+name);
                    
                }
            });
        }
    });
}

function call(mobile){
    ajax('/check_user_type',{},function(ret){
        console.log(ret.isSuccess);
        api.call({type: 'tel_prompt', number: mobile});
        ajax('/dial_log',{mobile:mobile},function(res){});
    })
}


function many_images(callback){
    var UIMediaScanner = api.require('UIMediaScanner');
        UIMediaScanner.open({
            type: 'picture',
            column: 4,
            classify: true,
            max: 9,
            sort: {
                key: 'time',
                order: 'desc'
            },
            texts: {
                stateText: '已选择*项',
                cancelText: '取消',
                finishText: '完成'
            },
            styles: {
                bg: '#fff',
                mark: {
                    icon: '',
                    position: 'bottom_left',
                    size: 20
                },
                nav: {
                    bg: '#eee',
                    stateColor: '#000',
                    stateSize: 18,
                    cancelBg: 'rgba(0,0,0,0)',
                    cancelColor: '#000',
                    cancelSize: 18,
                    finishBg: 'rgba(0,0,0,0)',
                    finishColor: '#000',
                    finishSize: 18
                }
            },
            scrollToBottom: {
                intervalTime: 3,
                anim: true
            },
            exchange: true,
            rotation: true
        }, function(ret) {
            if (ret.eventType == "confirm") {
                 var imgs_list=ret.list;
                 callback(imgs_list);
            }
        });
    }

 //检测更新
function checkUpdate() {
    var mam = api.require('mam');
    mam.checkUpdate(function(ret, err) {
        if (ret) {
            var result = ret.result;
            if (result.update == true && result.closed == false) {
                var str = '新版本型号:' + result.version + ';更新提示语:' + result.updateTip + ';下载地址:' + result.source + ';发布时间:' + result.time;
                api.confirm({
                    title : '有新的版本,是否下载并安装 ',
                    msg : str,
                    buttons : ['确定', '取消']
                }, function(ret, err) {
                    if (ret.buttonIndex == 1) {
                        if (api.systemType == "android") {
                            api.download({
                                url : result.source,
                                report : true
                            }, function(ret, err) {
                                if (ret && 0 == ret.state) {/* 下载进度 */
                                    api.toast({
                                        msg : "正在下载应用" + ret.percent + "%",
                                        duration : 2000
                                    });
                                }
                                if (ret && 1 == ret.state) {/* 下载完成 */
                                    var savePath = ret.savePath;
                                    api.installApp({
                                        appUri : savePath
                                    });
                                }
                            });
                        }
                        if (api.systemType == "ios") {
                            api.installApp({
                                appUri : result.source
                            });
                        }
                    }
                });
            } else {
                console.log('暂无更新！');
            }
        } else {
            api.alert({
                msg : err.msg
            });
        }
    });
}

function timestampFormat( timestamp ) {
    function zeroize( num ) {
        return (String(num).length == 1 ? '0' : '') + num;
    }

    var curTimestamp = parseInt(new Date().getTime() / 1000); //当前时间戳
    var timestampDiff = curTimestamp - timestamp; // 参数时间戳与当前时间戳相差秒数

    var curDate = new Date( curTimestamp * 1000 ); // 当前时间日期对象
    var tmDate = new Date( timestamp * 1000 );  // 参数时间戳转换成的日期对象

    var Y = tmDate.getFullYear(), m = tmDate.getMonth() + 1, d = tmDate.getDate();
    var H = tmDate.getHours(), i = tmDate.getMinutes(), s = tmDate.getSeconds();

    if ( timestampDiff < 60 ) { // 一分钟以内
        return "刚刚";
    } else if( timestampDiff < 3600 ) { // 一小时前之内
        return Math.floor( timestampDiff / 60 ) + "分钟前";
    } else if ( curDate.getFullYear() == Y && curDate.getMonth()+1 == m && curDate.getDate() == d ) {
        return '今天' + zeroize(H) + ':' + zeroize(i);
    } else {
        var newDate = new Date( (curTimestamp - 86400) * 1000 ); // 参数中的时间戳加一天转换成的日期对象
        if ( newDate.getFullYear() == Y && newDate.getMonth()+1 == m && newDate.getDate() == d ) {
            return '昨天' + zeroize(H) + ':' + zeroize(i);
        } else if ( curDate.getFullYear() == Y ) {
            return  zeroize(m) + '月' + zeroize(d) + '日 ' + zeroize(H) + ':' + zeroize(i);
        } else {
            return  Y + '年' + zeroize(m) + '月' + zeroize(d) + '日 ' + zeroize(H) + ':' + zeroize(i);
        }
    }
}

function unique(array){
  var n = {}, r = [], len = array.length, val, type;
  for (var i = 0; i < array.length; i++) {
    val = array[i];
    type = typeof val;
    if (!n[val]) {
      n[val] = [type];
      r.push(val);
    } else if (n[val].indexOf(type) < 0) {
      n[val].push(type);
      r.push(val);
    }
  }
  return r;
}